{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "原文代码作者：https://blog.csdn.net/GrinAndBearIt/article/details/79229803\n",
    "\n",
    "中文注释制作：机器学习初学者(微信公众号：ID:ai-start-com)\n",
    "\n",
    "配置环境：python 3.6\n",
    "\n",
    "代码全部测试通过。\n",
    "![gongzhong](../gongzhong.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 第11章 条件随机场\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 例11.1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from numpy import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "24.532530197109345\n",
      "24.532530197109352\n"
     ]
    }
   ],
   "source": [
    "#这里定义T为转移矩阵列代表前一个y(ij)代表由状态i转到状态j的概率,Tx矩阵x对应于时间序列\n",
    "#这里将书上的转移特征转换为如下以时间轴为区别的三个多维列表，维度为输出的维度\n",
    "T1=[[0.6,1],[1,0]];T2=[[0,1],[1,0.2]]\n",
    "#将书上的状态特征同样转换成列表,第一个是为y1的未规划概率，第二个为y2的未规划概率\n",
    "S0=[1,0.5];S1=[0.8,0.5];S2=[0.8,0.5]\n",
    "Y=[1,2,2]  #即书上例一需要计算的非规划条件概率的标记序列\n",
    "Y=array(Y)-1  #这里为了将数与索引相对应即从零开始\n",
    "P=exp(S0[Y[0]])\n",
    "for i in range(1,len(Y)):\n",
    "    P *= exp((eval('S%d' % i)[Y[i]])+eval('T%d' % i)[Y[i-1]][Y[i]])\n",
    "print(P)\n",
    "print(exp(3.2))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 例11.2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "非规范化概率 24.532530197109345\n"
     ]
    }
   ],
   "source": [
    "#这里根据例11.2的启发整合为一个矩阵\n",
    "F0=S0;F1=T1+array(S1*len(T1)).reshape(shape(T1));F2=T2+array(S2*len(T2)).reshape(shape(T2))\n",
    "Y=[1,2,2]  #即书上例一需要计算的非规划条件概率的标记序列\n",
    "Y=array(Y)-1\n",
    "\n",
    "P=exp(F0[Y[0]])\n",
    "Sum=P\n",
    "for i in range(1,len(Y)):\n",
    "    PIter=exp((eval('F%d' % i)[Y[i-1]][Y[i]]))\n",
    "    P *= PIter\n",
    "    Sum += PIter\n",
    "print('非规范化概率',P)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
